// index.ts
// 获取应用实例
const app = getApp<IAppOption>()

let cv: any;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatar_list: [
      '../../images/1.png',
      '../../images/2.png',
      '../../images/3.png',
      '../../images/4.png',
      '../../images/5.png',
      '../../images/6.png',
      '../../images/7.png',
      '../../images/8.png',
    ],
    nickName: '',
    avatar: '',
    temUrl: '',
    tempCtx: ''  // canvas实例 保存图片时用
  },

  onLoad() {

    // 获取节点实例
    cv = wx.createSelectorQuery().select('#myCanvas').fields({
      node: true,
      size: true,
    })

  },

  // 获取用户临时头像
  getAvatar(e: any) {
    const { detail } = e
    // 设置临时头像路径
    this.setData({
      avatar: detail.avatarUrl
    })
  },

  setAvatar(e: any) {

    // 获取图标地址
    this.setData({
      temUrl: e.currentTarget.dataset.url
    })


    let avatar = this.data.avatar
    let temUrl = e.currentTarget.dataset.url
    if (avatar == '' || avatar == undefined || temUrl == '' || temUrl == undefined) {
      wx.showToast({
        title: '请先获取头像',
        icon: 'error'
      })
      return
    }



    cv.exec((res: any) => {

      const canvas = res[0].node // 节点
      const ctx = canvas.getContext('2d') // 实例方法

      let x = 0
      let y = 0
      // 取canvas宽高
      let width = res[0].width * 1.7 + 10
      let height = res[0].height

      // 通过获取的canvas节点，创建两张图片
      let user = canvas.createImage() // 用户图片
      let temp = canvas.createImage() // 装饰图片的元素


      // 分别给他们赋值 用户图片的url和 装饰图片的url
      user.src = this.data.avatar
      temp.src = this.data.temUrl

      // 然后调用canvas实例的方法，把图片绘制到canvas标签上
      // 先画用户头像 后装饰图 盖住用户头像
      ctx.drawImage(user, x, y, width, height)
      ctx.drawImage(temp, x, y, width, height - 20)

      this.data.tempCtx = '1'

      wx.canvasToTempFilePath({
        x, y, width, height,
        destWidth: width + 20,
        destHeight: height * 2,
        canvas,
        success: (res) => {
          // 将生成的canvas 转临时图片链接
          this.setData({
            tempCtx: res.tempFilePath
          })
        },
        fail: (() => {
          this.setData({
            tempCtx: ''
          })
        })
      })

    })

  },


  saveAvatar() {
    let isTemp = this.data.tempCtx

    if (isTemp == '') {
      wx.showToast({ title: '暂无可保存内容', icon: 'error' })
      return
    }

    // 把图片保存到相册
    wx.saveImageToPhotosAlbum({
      filePath: isTemp,
      success: (res) => {
        console.log(res, '保存成功');
      },
      fail: (err) => {
        console.log(err, '保存失败');
      }
    })

  },


  onShareAppMessage(): WechatMiniprogram.Page.ICustomShareContent {
    return {
      title: '国庆头像制作'
    }
  }
})
